package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;

import com.api.shopapi.common.WaterMark;
import com.api.shopapi.entity.MyResult;
import com.api.shopapi.entity.PreCheck;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


//图片上传

@RestController
@RequestMapping("Upload")
public class UploadController extends BaseController{



    @RequestMapping(value = "AddPictures", method = RequestMethod.POST)
    public String AddPictures(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String fileName = file.getOriginalFilename();

        String filePath = "E:\\java\\IDEA Project\\institutionapi\\institution\\src\\main\\resources\\file\\";
        File dest =new File(filePath+fileName);
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }


    @RequestMapping("Add")
    public String Add(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String filePath = "E:\\java\\IDEA Project\\institutionapi\\institution\\src\\main\\resources\\file\\";
        File dest =new File(filePath+fileName);
        try {
            Thumbnails.of(file.getInputStream()).size(200,300).toFile(dest);
            return "上传成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";


    }







    //上传图片并压缩
    @RequestMapping(value = "Imgs",method = RequestMethod.POST)
    public MyResult Imgs(@RequestParam("file") MultipartFile file,
                         @RequestParam("timeStr") String timeStr,
                         @RequestParam("sign") String sign,
                         @RequestParam("staffCode") String staffCode) {

        try{

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Upload/Imgs");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            if (file.isEmpty()) {
                return failed("文件不存在");
            }

            String fileName = file.getOriginalFilename();

            if(!isImg(fileName)){
                return failed("非图片格式不能上传");
            }

            String suffix = getSuffix(fileName);

            File file1 = new File(imgsRootPath);
            if (!file1.exists()) {//如果文件夹不存在
                file1.mkdirs();//创建文件夹
            }

            File file2 = new File(rootPath);
            if (!file2.exists()) {//如果文件夹不存在
                file2.mkdirs();//创建文件夹
            }


            String fdPath = imgsRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdirs();
            }

            String filePath = fdPath + "\\" +  getTimeStr() + suffix;
            File dest =new File(filePath);

            String filePath64 = filePath + "_64x64"+suffix;
            File dest64 =new File(filePath64);

            String filePath310 = filePath + "_310x310"+suffix;
            File dest310 =new File(filePath310);



            try {

                Thumbnails.of(file.getInputStream()).size(64,64).toFile(dest64);
                Thumbnails.of(file.getInputStream()).size(310,310).toFile(dest310);

                Thumbnails.of(file.getInputStream()).size(800,800).toFile(dest);

                //file.transferTo(dest);

            } catch (Exception e) {
                return failed("上传失败:"+e.getMessage());
            }


            JSONObject jsonObject1 = new JSONObject();
            String rtPath = filePath.replace(rootPath,"").replace("\\","/");
            jsonObject1.put("path",rtPath);

            return success(jsonObject1);

        }catch (Exception e){
            insertError("/Upload/Imgs","",getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //上传文件
    @RequestMapping(value = "File",method = RequestMethod.POST)
    public MyResult File(@RequestParam("file") MultipartFile file,
                         @RequestParam("timeStr") String timeStr,
                         @RequestParam("sign") String sign,
                         @RequestParam("staffCode") String staffCode) {

        try{

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Upload/File");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            if (file.isEmpty()) {
                return failed("文件不存在");
            }

            String fileName = file.getOriginalFilename();

            int i = fileName.lastIndexOf(".");
            String fileName1=fileName.substring(0,i);

            if(!isFile(fileName)){
                return failed("非正确的文件格式不能上传");
            }

            String suffix = getSuffix(fileName);


            String fdPath = filesRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdirs();
            }

            String filePath = fdPath + "\\" +fileName1+getTimeStr() + suffix;
            File dest =new File(filePath);

            OutputStream os = null;
            InputStream inputStream = file.getInputStream();

            try {

                os = new FileOutputStream(filePath);
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;

                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                os.close();
                inputStream.close();

                //file.transferTo(dest);

            } catch (Exception e) {
                return failed("上传失败:"+e.getMessage());
            }


            JSONObject jsonObject1 = new JSONObject();
            String rtPath = filePath.replace(rootPath,"").replace("\\","/");
            jsonObject1.put("path",rtPath);

            return success(jsonObject1);

        }catch (Exception e){
            return anomalous(e.getMessage());
        }

    }










    //上传商品分类的图标
    @RequestMapping(value = "GoodsClassIcon",method = RequestMethod.POST)
    public MyResult GoodsClassIcon(@RequestParam("file") MultipartFile file,
                                   @RequestParam("timeStr") String timeStr,
                                   @RequestParam("sign") String sign,
                                   @RequestParam("staffCode") String staffCode) {

        try{

//            if(!checkSignPC(timeStr,sign)){
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Upload/GoodsClassIcon");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            if (file.isEmpty()) {
                return failed("文件不存在");
            }

            String fileName = file.getOriginalFilename();

            if(!isImg(fileName)){
                return failed("非图片格式不能上传");
            }

            String suffix = getSuffix(fileName);


            String fdPath = imgsRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdir();
            }

            String newFileName = getTimeStr() + suffix;

            String filePath = fdPath + "\\" + newFileName;
            File dest =new File(filePath);
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                return failed("上传失败");
            }


            JSONObject jsonObject1 = new JSONObject();
            String rtPath = filePath.replace(rootPath,"").replace("\\","/");
            jsonObject1.put("path",rtPath);

            return success(jsonObject1);

        }catch (Exception e){
            return anomalous(e.getMessage());
        }

    }





    //上传商品的导航图
    @RequestMapping(value = "GoodsHead",method = RequestMethod.POST)
    public MyResult GoodsHead(@RequestParam("file") MultipartFile file,
                              @RequestParam("timeStr") String timeStr,
                              @RequestParam("sign") String sign,
                              @RequestParam("staffCode") String staffCode) {

        try{

//            if(!checkSignPC(timeStr,sign)){
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Upload/GoodsHead");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            if (file.isEmpty()) {
                return failed("文件不存在");
            }

            String fileName = file.getOriginalFilename();

            if(!isImg(fileName)){
                return failed("非图片格式不能上传");
            }

            String suffix = getSuffix(fileName);


            String fdPath = imgsRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdir();
            }

            String filePath = fdPath + "\\" +  getTimeStr() + suffix;
            File dest =new File(filePath);

            String filePath64 = filePath + "_64x64"+suffix;
            File dest64 =new File(filePath64);

            String filePath310 = filePath + "_310x310"+suffix;
            File dest310 =new File(filePath310);

            try {

                Thumbnails.of(file.getInputStream()).size(64,64).toFile(dest64);
                Thumbnails.of(file.getInputStream()).size(310,310).toFile(dest310);

                file.transferTo(dest);

            } catch (Exception e) {
                return failed("上传失败:"+e.getMessage());
            }


            JSONObject jsonObject1 = new JSONObject();
            String rtPath = filePath.replace(rootPath,"").replace("\\","/");
            jsonObject1.put("path",rtPath);

            return success(jsonObject1);

        }catch (Exception e){
            return anomalous(e.getMessage());
        }

    }



    //上传商品的详情
    @RequestMapping(value = "GoodsImgDetail",method = RequestMethod.POST)
    public MyResult GoodsImgDetail(@RequestParam("file") MultipartFile file,
                                   @RequestParam("timeStr") String timeStr,
                                   @RequestParam("sign") String sign,
                                   @RequestParam("staffCode") String staffCode) {

        try{


//            if(!checkSignPC(timeStr,sign)){
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Upload/GoodsImgDetail");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            if (file.isEmpty()) {
                return failed("文件不存在");
            }

            String fileName = file.getOriginalFilename();

            if(!isImg(fileName)){
                return failed("非图片格式不能上传");
            }

            String suffix = getSuffix(fileName);


            String fdPath = imgsRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdir();
            }

            String filePath = fdPath + "\\" +  getTimeStr() + suffix;
            File dest =new File(filePath);

            try {

                file.transferTo(dest);

            } catch (Exception e) {
                return failed("上传失败");
            }


            JSONObject jsonObject1 = new JSONObject();
            String rtPath = filePath.replace(rootPath,"").replace("\\","/");
            jsonObject1.put("path",rtPath);

            return success(jsonObject1);

        }catch (Exception e){
            return anomalous(e.getMessage());
        }

    }

    //上传图片并压缩加水印
    @RequestMapping(value = "ImgsWaterMark",method = RequestMethod.POST)
    public MyResult ImgsWaterMark(@RequestParam("file") MultipartFile file,
                                  @RequestParam("timeStr") String timeStr,
                                  @RequestParam("sign") String sign,
                                  @RequestParam("staffCode") String staffCode) {

        try{

//            if(!checkSignPC(timeStr,sign)){
//                return failed("签名错误");
//            }
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Upload/ImgsWaterMark");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            if (file.isEmpty()) {
                return failed("文件不存在");
            }

            String fileName = file.getOriginalFilename();

            if(!isImg(fileName)){
                return failed("非图片格式不能上传");
            }

            String suffix = getSuffix(fileName);


            String fdPath = imgsRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdir();
            }

            String filePath = fdPath + "\\" +  getTimeStr() + suffix;
            File dest =new File(filePath);

            String filePath64 = filePath + "_64x64"+suffix;
            File dest64 =new File(filePath64);

            String filePath310 = filePath + "_310x310"+suffix;
            File dest310 =new File(filePath310);

            try {

                Thumbnails.of(file.getInputStream()).size(64,64).toFile(dest64);
                Thumbnails.of(file.getInputStream()).size(310,310).toFile(dest310);

                file.transferTo(dest);




                Font font = new Font("微软雅黑", Font.PLAIN,32);
                String srcImgPath = filePath;
                String tarImgPath = filePath + "_watermark.jpg";
                String watermarkContent = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                Color color = new Color(255, 0, 0,128);
                WaterMark aa = new WaterMark();
                aa.addWatermark(srcImgPath, tarImgPath, watermarkContent, color, font);


            } catch (Exception e) {
                return failed("上传失败:"+e.getMessage());
            }


            JSONObject jsonObject1 = new JSONObject();
            String rtPath = filePath.replace(rootPath,"").replace("\\","/");
            jsonObject1.put("path",rtPath);

            return success(jsonObject1);

        }catch (Exception e){
            insertError("/Upload/ImgsWaterMark","",getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "ReadFile", method = RequestMethod.GET)
    public MyResult getUrlFile(@RequestParam("url") String url, HttpServletResponse response) {
        try {
            String serverUrl = filesRootPath;
            String url1=url.substring(1);
            String imgUrl = serverUrl + url1.substring(url1.indexOf('/'));
            File file = new File(imgUrl);
            // 后缀名
//            String suffixName = url.substring(url.lastIndexOf("."));
//            String imgType = "image/" + suffixName;
            //判断文件是否存在如果不存在就返回默认图标
            if (!(file.exists() && file.canRead())) {
                return failed("文件不存在");
            }
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            response.setContentType("application/json;charset=utf-8");
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            e.printStackTrace();
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "ReadImg", method = RequestMethod.GET)
    public MyResult ReadImg(@RequestParam("url") String url, HttpServletResponse response) {
        try {
            String serverUrl = rootPath;
            String imgUrl = serverUrl + url;
            File file = new File(imgUrl);
            // 后缀名
//            String suffixName = url.substring(url.lastIndexOf("."));
//            String imgType = "image/" + suffixName;
            //判断文件是否存在如果不存在就返回默认图标
            if (!(file.exists() && file.canRead())) {
                return failed("图片不存在");
            }
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            response.setContentType("application/json;charset=utf-8");
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            e.printStackTrace();
            return anomalous(getExceptionMsg(e));
        }
    }
}
